package com.xinnet.mms.customtransfer.service.impl;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.customerConsumeManage.dao.CustomerConsumeManageDao;
import com.xinnet.mms.customerManage.dao.CustomerManageDao;
import com.xinnet.mms.customerstate.dao.CustomerStateHistDao;
import com.xinnet.mms.customtransfer.service.IntentionCustomTransferService;
import com.xinnet.mms.empcustomrelation.dao.EmpCustomRelationDao;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.CustomerConsume;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.entity.PublicConfig;
import com.xinnet.mms.utils.CustomerManage;
import com.xinnet.mms.utils.CustomerType;
import com.xinnet.mms.utils.DateUtil;

@Service("intentionCustomTransferService")
public class IntentionCustomTransferServiceImpl implements IntentionCustomTransferService{
	@Autowired
	private CustomerManageDao customerManageDao;
	@Autowired
	private CustomAllotService customAllotService;
	@Autowired
	private CustomerStateHistDao customerStateHistDao;
	@Autowired
	private EmpCustomRelationDao  empCustomRelationDao;
	@Autowired
	private CustomerConsumeManageDao  customConsumeDao;
	
	private static Logger log=LoggerFactory.getLogger(IntentionCustomTransferServiceImpl.class);
	/**
	 * 意向客户流转
	 * @throws SQLException 
	 */
	public void intentionCustomTransfer() throws Exception{
		//获取流转规则
		 Map<String,Product> productRuleMap = AppGlobalContainer.productRuleMap;
		if(productRuleMap==null || productRuleMap.isEmpty()){
			log.info("没有可用的流转规则");
			return;
		}
		//获取意向客户信息
		Map<Integer,List<EmpCustomRelation>> customerMap = (Map<Integer,List<EmpCustomRelation>>)AppGlobalContainer.transferCustomMap;
		if(customerMap==null || customerMap.isEmpty()){
			log.info("客户为空");
			return;
		}
			
		List<EmpCustomRelation> intentionCustomList = customerMap.get(CustomerType.INTENTION_CUSTOMER);
		if(intentionCustomList==null || intentionCustomList.isEmpty()){
			log.info("意向客户为空");
			return;
		}
       String isTest = ConfigUtil.getString("isTest");
       if(isTest==null || "".equals(isTest)){
       	log.error("配置异常：是否是测试环境");
       	return;
       }
       log.info("************************************************************************************意向客户流转结束********************************************");
		//意向客户流转操作
		for (Iterator<EmpCustomRelation> iterator = intentionCustomList.iterator(); iterator.hasNext();){
			EmpCustomRelation intentionCustom = (EmpCustomRelation) iterator.next();
			this.customTransferForIntentionCustomer(intentionCustom, isTest);
		}
		intentionCustomList=null;
		log.info("************************************************************************************意向客户流转结束********************************************");
	}
	
	/**
	 * 对每个意向客户流转
	 * @param newRegisterCustom
	 * @param isTest
	 * @param transferRuleList
	 * @throws Exception
	 */
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false,rollbackFor=Exception.class)
	public void customTransferForIntentionCustomer(EmpCustomRelation intentionCustom,String isTest){
		String customId = intentionCustom.getCustomId();
		try {
			String productId = intentionCustom.getProductId();
			String productCode = intentionCustom.getProductCode();
			if(productId==null || "".equals(productId)){
				log.info("当前产品ID: is null  return");
				return;
			}
			if(productCode==null || "".equals(productCode)){
				log.info("当前产品CODE: is null  return");
				return;
			}
			String empNo = intentionCustom.getEmpId();
			String pushHistId = intentionCustom.getPushHistId();
			java.util.Date createTime = intentionCustom.getCreateTime();
			if(productId==null){
				return;
			}
			//获取当前产品规则
			Product currentProductRule=AppGlobalContainer.productRuleMap.get(productId);
			if(currentProductRule==null){
				log.error("当前产品规则为空!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				return;
			}
			//计算停留超时时间
			Integer holdtime = currentProductRule.getPushNodealholdtime();
			if(holdtime==null){
				return;
			}
			Calendar calendar=Calendar.getInstance();
			calendar.setTime(createTime);
			if("true".equals(isTest)){
				calendar.add(Calendar.MINUTE, holdtime);
			}else if("false".equals(isTest)){
				calendar.add(Calendar.DATE, holdtime);
			}else{
				return;
			}
			Date saleHoldTime=calendar.getTime();
			Date nowDate= new Date();
			if(nowDate.after(saleHoldTime)){
				//是否是服务期客户
				Customer customer = customAllotService.getCustomerById(customId);
				Integer tempCustomerType = customer.getCustomerType();
				if(tempCustomerType==CustomerManage.SERVICE_CUSTOMER){
					//服务期客户 删除 销售客户对应关系 记录日志
					empCustomRelationDao.delEmpCustomRelationByCustomIdAndEmpNo(customId,empNo,productCode);
					customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);
				}else{
					Map<String,List<EmpCustomRelation>> empCustomRelationMap = AppGlobalContainer.empCustomRelationMap;
					List<EmpCustomRelation> empCustomRelationList = empCustomRelationMap.get(customId);
					//获取可用的业绩保留期
					Map<String,PublicConfig> scoreHoldDateMap = AppGlobalContainer.scoreHoldDateMap;
					PublicConfig  publicConfig = scoreHoldDateMap.get("scoreHoldTime");
					boolean isCanGoOpenSea = this.isCanGoOpenSeaByScoreHoldTime(publicConfig,customId);
					if((empCustomRelationList==null || empCustomRelationList.size()<=1) && isCanGoOpenSea){
						//当前客户为最后一个管理的销售 人员  并且没有其他销售管理此用户 进公海记日志
						Customer intentionCustomer = new Customer();
						intentionCustomer.setCusId(customId);
						intentionCustomer.setCustomerType(CustomerManage.OPEN_SEA_CUSTOMER);
						customerManageDao.updateCustomType(intentionCustomer);
						intentionCustomer.setPushHistId(pushHistId);
						customAllotService.allot(intentionCustomer,CustomerManage.OPEN_SEA_CUSTOMER);
						log.info("意向客户进入公海：customer id"+customId+"  "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					}
					//当前销售不是最后一个此客户的管理人：删除 销售客户对应关系 记录日志
					empCustomRelationDao.delEmpCustomRelationByCustomIdAndEmpNo(customId,empNo,productCode);
					customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);
					}
				}	
			
		} catch (Exception e) {
			// TODO: handle exception
			//e.printStackTrace();
			log.error("新注册客户异常：customer id"+customId+"  "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),e);
		}
		
		
	}
	
	/**
	 * 根据业绩保留期 客户是否可以进入公海
	 * @param publicConfig
	 * @param createTime
	 * @return
	 */
	private boolean isCanGoOpenSeaByScoreHoldTime(PublicConfig publicConfig,String customId){
		if(publicConfig==null){
			return true;
		}
		String scoreHoldTime = publicConfig.getConfigValue();
		if(scoreHoldTime==null || "".equals(scoreHoldTime)){
			return true;
		}
		boolean isCanGoOpenSea = customerStateHistDao.isCanGoOpenSeaByScoreHoldTime(customId,scoreHoldTime);
		return isCanGoOpenSea;
	}
	/**
	 * 流至意向客户的状态变更 处理和记录
	 * 
	 * 变更记录的表：custom , emp_cutom_relation , custom_state_hist
	 */
	@Override
	public void handlerToIntentionCustomer(CustomerConsume customerConsume) {
		
		
		try {
			//1.获取客户传入前的状态 emp_customer_relation
			String customId = customerConsume.getCusId();
			//2.更改状态(三张表)
			Customer intentionCustomer = new Customer();
			intentionCustomer.setCusId(customId);
			intentionCustomer.setCustomerType(CustomerManage.INTENTION_CUSTOMER);
			customerManageDao.updateCustomType(intentionCustomer);
			
			//新注册用户没有用户销售关系表数据，在此拼装数据插入
			Customer custom = customerManageDao.getCustomById(intentionCustomer);

			List <EmpCustomRelation> empCustomRelationList = empCustomRelationDao.getEmpCustomRelationByCustomId(customId);
			if(empCustomRelationList.isEmpty()){
				EmpCustomRelation empCustomRelation=new EmpCustomRelation();
				empCustomRelation.setId(UUID.randomUUID().toString());
				empCustomRelation.setCustomId(custom.getCusId());
				empCustomRelation.setEmpId(customerConsume.getEmpId());
				empCustomRelation.setCustomType(CustomerManage.INTENTION_CUSTOMER);
				empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
				empCustomRelation.setProductId("");
				empCustomRelation.setProductCode(customerConsume.getProduct());
				empCustomRelation.setPushHistId("");
				empCustomRelation.setPusherId("");
				empCustomRelation.setPushDesc("流转至意向客户");
				empCustomRelation.setDeptno("");
				empCustomRelation.setCompanyId(custom.getCompanyId());
				empCustomRelationDao.addEmpCustomRelation(empCustomRelation);
			}else{
				//已经有用户销售关系的，更新数据
				EmpCustomRelation empCustomRelation = empCustomRelationList.get(0);
				empCustomRelation.setCustomType(CustomerManage.INTENTION_CUSTOMER);
				empCustomRelationDao.updateEmpCustomRelationById(empCustomRelation);
			}
			
			
			//添加客户状态变更记录
			CustomStateHist customStateHist=new CustomStateHist();
			customStateHist.setId(UUID.randomUUID().toString());
			customStateHist.setProductId("");
			customStateHist.setCustomId(customId);
			customStateHist.setCustomType(CustomerManage.INTENTION_CUSTOMER);
			customStateHist.setCustomState(CustomerManage.ACCEPT_YES);
			customStateHist.setEmpId(customerConsume.getEmpId());
			customStateHist.setPusherId("");
			customStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
			customStateHist.setPushHistId("");
			customStateHist.setPushDesc("");
			customStateHist.setProductCode(customerConsume.getProduct());
			customStateHist.setStartTime(DateUtil.getSysDate().toString());
			
			customerStateHistDao.addCustomerStateHist(customStateHist);
		} catch (SQLException e) {
			log.info("意向客户状态变更失败！");
			e.printStackTrace();
		}
		
		
		
		
		//3.保存更改记录
	}
}
